<?php

namespace App\V3\V3_2_6\Controllers;

use Illuminate\Http\Request;
use OSS\OssClient;

class UploadController extends BaseController
{
    protected $ossClient;

    public function __construct(Request $request)
    {
        parent::__construct($request);

        $this->ossClient = new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint'),
        );
    }

    /**
     * 图片上传
     * @param Request $request
     * 2022/8/18 10:09
     * Author: Sun Wu
     * @return array|\Illuminate\Http\JsonResponse|string[]
     */
    public function upload(Request $request)
    {
        $files = $request->file('images');
        if(empty($files)) {
            return $this->fail('', '请选择图片');
        }

        $fileSize = $files->getSize();

        if($fileSize > 2097152) {
            //return ['code' => 1, 'msg' => '图片大小不能超出2M', 'data' => ''];
            return $this->fail('', '图片大小不能超出2M');
        }

        if(!in_array($files->extension(), ['jpg', 'jpeg', 'png'])) {
            //return ['code' => '1', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`', 'data' => ''];
            return $this->fail('', '不支持的图片格式，当前仅支持`png`和`jpg`以及`jpeg`');
        }

        $uploadPath = $files->store(date('Y').'/'.date('m').'/'.date('d'));

        $fullPath = '/uploads/'.$uploadPath;
        $ossPath = ltrim($fullPath, './');
        $path = public_path().$fullPath;

        $result = saveFileSize(
            ['main_id' => $this->getMainUserId()],
            $fileSize,
            []
        );

        if($result['code']) {
            //删除服务器上传后存储的图片
            unlink($path);

            return response()->json(
                $result
            );
        }

        $client = $this->ossClient;

        /**
         * @param $ossPath oss服务器路径
         * @param $path 服务器图片绝对路径
         * @param config('app.aliyun_oss_bucket') 目标bucket
         */
        $client->uploadFile(config('app.aliyun_oss_bucket'),  $ossPath, $path);

        //删除服务器上传后存储的图片
        unlink($path);

        return $this->success(config('app.aliyun_oss_bucket_url').$fullPath);
    }
}
